home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: simple code, argc, argv, strcmp()
- Date: Thu, 1 Feb 1996 12:51:04 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9602011151.AA04526@dxmint.cern.ch>
- References: <11f7cc$17261a.3b3@daprez>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- otisg@panther.middlebury.edu (Otis Gospodnetic) writes:
-
- >usage: <program> -e [SourceFile] RemoteFile
- > or
- > <program> -d [InFile]
- >
- >if the person doesn't use this right the program is supposed to call Usage()
- >which is not here, but it's in my code, and if the person calls the program
- >the correct way one of the two actions should be taken (encode or decode).
- >
- >Problem - I am doing something wrong and I almost always end up calling
- >Usage() even if I use the program correctly.
- >
- >int main (int argc, char **argv) {
- >
- > if (!strcmp(argv[1],"-d") || !strcmp(argv[1],"-e")) {
- > Usage();
- > }
- ...
- >
- >Can someone see what's wrong with this ?
- >am I not using strcmp() right ?
-
- Right :-)
-
- Your code is equivalent to:
-
- if (strcmp(argv[1],"-d") == 0 || strcmp(argv[1],"-e") == 0) Usage();
-
- Which means that any time the program is correctly invoked, it will call
- Usage!
-
- So:
-
- 1. Never use ! with strcmp. It's a good way to shoot yourself in the foot.
-
- 2. Always check what a function is supposed to return before using it.
- strcmp returns 0 when the strings are equal.
-
- 3. Are you sure you didn't mean && when you wrote ||? Even if !strcmp()
- would have worked as you thought it did, the || operator would have
- caused the expression inside the if statement to _always_ evaluate to 1.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-